import java.util.NoSuchElementException;

public class MyBST {
    //先实现一棵树
    private TreeNode root;
    private int size;
    private static class TreeNode{
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }
    //查找最大值
    public int max(){
        if(size==0){
            throw new NoSuchElementException("tree is empty");
        }
        TreeNode maxNode=findMaxNode(root);
        return maxNode.val;
    }

    private TreeNode findMaxNode(TreeNode root) {
        if(root.right==null){
            return root;
        }
        return findMaxNode(root.right);
    }
    //查找最小值
    public int min() {
        if (size == 0) {
            throw new NoSuchElementException("tree is empty");
        }
        TreeNode minNode=findMinNode(root);
        return minNode.val;
    }

    private TreeNode findMinNode(TreeNode root) {
        if(root.left==null){
            return root;
        }
        return findMinNode(root.left);
    }
    //添加元素
    public void add(int val){
        root=add(root,val);
    }
    private TreeNode add(TreeNode root,int val){
        if(root==null){
            TreeNode node=new TreeNode(val);
            size++;
            return node;
        }else if(root.val<val){
            root.right=add(root.right,val);
            return root;
        }
        root.left=add(root.left,val);
        return root;
    }
}
